package com.cl.controller.supplier;


import java.util.Map;
import java.util.ResourceBundle;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cl.controller.BaseController;
import com.cl.interceptor.Auth;
import com.cl.model.bean.SessionUserM;
import com.cl.util.Pager;
import com.cl.util.WebApiUtil;

/**
 * 供应商协同controller
 * @author chenlu
 * @date 2018-5-19 下午5:32:14
 */
@Controller
@RequestMapping("/supplier")
public class SupplierController extends BaseController{

	private Boolean webApiLogin(){
		Boolean isLogin = false;
		try{
			// 读取配置文件
			ResourceBundle rb = ResourceBundle.getBundle("config");

			// 配置连接参数
			WebApiUtil.POST_K3CloudURL = rb.getString("cloudUrl");
	    	String dbId = rb.getString("dbId");
	    	String uid = rb.getString("uid");
	    	String pwd = rb.getString("pwd");
	    	int lang = 2052;
	    	isLogin =  WebApiUtil.Login(dbId, uid, pwd, lang);	    	
		}catch (Exception e) {
			e.printStackTrace();
		}
		return isLogin;
	}
	
	/**
	 * 简单登录
	 * @param response
	 * @param userName
	 * @param password
	 */
	@RequestMapping("/login")
	public void login(HttpServletResponse response,HttpServletRequest request,String userName,String password){
        
        try {
			if (webApiLogin()) {
				String sContent = "{\"userName\":\""+userName+"\", \"pwd\":\""+password+"\"}";
				String rs = WebApiUtil.SupplierLogin(sContent);
				JSONObject rootData = JSONObject.parseObject(rs);
				if(rootData.get("IsSuccess").toString().equals("true")){
					SessionUserM sessionUserM = new SessionUserM();
					String supplierId = rootData.get("supplierId").toString();
					String supplierName = rootData.get("supplierName").toString();
					sessionUserM.setSupplierName(supplierName);
					sessionUserM.setSupplierId(supplierId);
					sessionUserM.setUserName(userName);
					sessionUserM.setPassword(password);
					setCurrSessionUserM(sessionUserM);
					sendSingleSuccessMsg(response, "登录成功");
				}else{
					sendSingleErrorMsg(response, "用户名或密码不正确,请检查后再登录!");
				}

			 }else{
				 sendSingleErrorMsg(response, "连接失败！请联系管理员");
			 }
			
			//调用接口
//			if(userName.equals("0001") && password.equals("0001")){
//				SessionUserM sessionUserM = new SessionUserM();
//				sessionUserM.setSupplierName("测试供应商");
//				sessionUserM.setUserName(userName);
//				sessionUserM.setPassword(password);
//				setCurrSessionUserM(sessionUserM);
//				sendSingleSuccessMsg(response, "登录成功");
//			}else{
//				sendSingleErrorMsg(response, "用户名或密码不正确,请检查后再登录!");
//			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * 登出
	 * @return
	 */
	@RequestMapping("/loginOut")
	public void loginOut(HttpServletResponse response){
		setCurrSessionUserM(null);
		sendSingleSuccessMsg(response, "成功");
	}
	
	/**
	 * 修改密码界面
	 * @return
	 */
	@Auth(verifyLoginM=true)
	@RequestMapping("/prepareUpdatePsw")
	public ModelAndView prepareUpdatePsw(@RequestParam Map<String,Object> map){
		return forward("pc/supplier/updatePsw", map);
	}
	
	/**
	 * 修改密码
	 * @return
	 */
	@Auth(verifyLoginM=true)
	@RequestMapping("/updatePsw")
	public void updatePsw(String password,HttpServletResponse response){
		try {
			//调用接口
			if (webApiLogin()) {
				String sContent = "{\"supplierId\":\""+getCurrSessionUserM().getSupplierId()+"\", \"pwd\":\""+password+"\"}";
				String rs = WebApiUtil.UpdateSupplierPwd(sContent);
				JSONObject rootData = JSONObject.parseObject(rs);
				if(rootData.getBooleanValue("IsSuccess")){
					cleanSession();
					sendSingleSuccessMsg(response, "修改成功，请重新登录");
				}else{
					sendSingleErrorMsg(response, rootData.getString("msg"));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			sendSingleErrorMsg(response, e.getMessage());
		}
	}
	
	/**
	 * 采购订单列表
	 * @param map
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Auth(verifyLoginM=true)
	@RequestMapping("/purList")
	public ModelAndView purList(@RequestParam Map<String,Object> map,Pager pager){
		try{
			if(webApiLogin()){
				String startDate = (String)map.get("startDate");
				String endDate = (String)map.get("endDate");
				String keyword = (String)map.get("keyword");
				JSONObject para = new JSONObject();
				para.put("supplierId", getCurrSessionUserM().getSupplierId());
				para.put("SUPPLIER", getCurrSessionUserM().getSupplierName());
				para.put("startDate", startDate);
				para.put("endDate", endDate);
				para.put("orderNo", keyword);
				para.put("pageSize", pager.getPageSize());
				para.put("pageIndex", pager.getPage());
				String sContent =para.toJSONString();
				
				String rs = WebApiUtil.PurList(sContent);
				JSONObject rootData = JSONObject.parseObject(rs);
				JSONObject data = rootData.getJSONObject("Data");
				int total = Integer.parseInt(data.get("total").toString());
				JSONArray list = data.getJSONArray("rows");
				
				pager.setList(list);
				pager.setTotleCount(total);
				map.put("pager", pager);
				
			}
		}
		catch (Exception e) {
			// TODO: handle exception
		}
		return forward("pc/supplier/pur_list", map);
		//调用接口
//		JSONArray list = new JSONArray();
//		for (int i = 0; i < 3; i++) {
//			JSONObject json = new JSONObject();
//			json.put("FID", i);
//			json.put("FBILLNO", "CG000"+i);
//			json.put("FDATE", "2018-05-23");
//			json.put("SUPPLIER", "测试供应商");
//			json.put("FBILLALLAMOUNT", 20000);
//			json.put("F_PKSD_DDZT", "10");
//			json.put("F_PKSD_YJFHRQ", "2018-05-24");
//			list.add(json);
//		}
//		pager.setList(list);
//		pager.setTotleCount(3);
//		map.put("pager", pager);
//		return forward("pc/supplier/pur_list", map);
	}
	
	/**
	 * 进入更新采购订单状态界面
	 * @return
	 */
	@Auth(verifyLoginM=true)
	@RequestMapping("/prepareEdit")
	public ModelAndView prepareEdit(@RequestParam Map<String,Object> map){
		try{
			if(webApiLogin()){
				String orderId = map.get("id").toString();
				String sContent = "{orderId:"+orderId+"}";
				String rs = WebApiUtil.PurDetail(sContent);
				JSONObject rootData = JSONObject.parseObject(rs);
				JSONObject data = rootData.getJSONObject("Data");
				data.put("SUPPLIER", getCurrSessionUserM().getSupplierName());
				map.put("pur", data);
			}
		}catch (Exception e) {
			// TODO: handle exception
		}
		//调用接口
//		JSONObject json = new JSONObject();
//		json.put("FID", 1);
//		json.put("FBILLNO", "CG0001");
//		json.put("FDATE", "2018-05-23");
//		json.put("SUPPLIER", "测试供应商");
//		json.put("FBILLALLAMOUNT", 20000);
//		JSONArray entry = new JSONArray();
//		for (int i = 0; i < 2; i++) {
//			JSONObject t = new JSONObject();
//			t.put("MATERIALNAME", "测试物料");
//			t.put("FMODEL", "XXX");
//			t.put("FQTY", 3);
//			t.put("UNIT", "个");
//			t.put("FPRICE", 2000);
//			t.put("FENTRYAMOUNT", 6000);
//			entry.add(t);
//		}
//		json.put("entry", entry);
//		map.put("pur", json);
		return forward("pc/supplier/pur_edit", map);
	}
	
	/**
	 * 更新采购订单状态
	 * @return
	 */
	@Auth(verifyLoginM=true)
	@RequestMapping("/updatePurState")
	public void updatePurState(@RequestParam Map<String,Object> map,HttpServletResponse response){
		String orderId = (String)map.get("FID");
		String ddzt = (String)map.get("ddzt");
		String yjfhrq = (String)map.get("yjfhrq");
		String wldh = (String)map.get("wldh");
		try {
			//调用接口
			if(webApiLogin()){
				JSONObject para = new JSONObject();
				para.put("FID", orderId);
				para.put("ddzt", ddzt);
				para.put("yjfhrq", yjfhrq);
				para.put("wldh", wldh);
				String sContent = para.toJSONString();
				String rs = WebApiUtil.UpdatePur(sContent);
				JSONObject rootData = JSONObject.parseObject(rs);
				if(rootData.getBooleanValue("IsSuccess")){
					sendSingleSuccessMsg(response, "更新成功!");
				}else{
					sendSingleErrorMsg(response, rootData.getString("msg"));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			sendSingleErrorMsg(response, e.getMessage());
		}
	}
}
